import express from "express";
import getTimeToData from "../common/getTimeToData.ts";

const calendarShowData = express.Router();

const detailData = async (params: any) => {
    let paramsTime:any =  [];
    const [year, month] = params.month.split("-").map(Number);
    // 构建开始时间和结束时间的日期字符串
    const startDate = `${year}-${month}-01 00:00:00`;
    const endDate = `${year}-${month + 1}-01 00:00:00`;
    // 将日期字符串转换为时间戳
    const startTimestamp = new Date(startDate).getTime();
    const endTimestamp = new Date(endDate).getTime() - 1;
    paramsTime = [startTimestamp, endTimestamp];

    // 根据时间获取所有消费表的数据
    const res: any = await getTimeToData("consumptionRecord", paramsTime);

    const resStatistics = res.reduce((acc, cur) => {
        // 提取日期部分
        const date = cur.tradingTime.toISOString().split('T')[0];
        // 如果日期已存在，累加 amount，否则初始化为当前 amount
        if (acc[date]) {
            acc[date] += cur.amount;
        } else {
            acc[date] = cur.amount;
        }
        return acc;
    }, {});

    // 累加出现了精度问题进行处理一下
    Object.keys(resStatistics).forEach((key) => {
        resStatistics[key] = Number(resStatistics[key].toFixed(2));
    })

    return resStatistics;
};

calendarShowData.post("/calendarShow", async (req, res) => {
    try {
        const params = req.body;
        const dataRes: any = await detailData(params); // Wait for the query to complete
        res.send({
            code: 200,
            message: "日历消费总览 请求成功！",
            result: dataRes,
        });
    } catch (error) {
        console.error("Error fetching file records:", error);
        res.status(500).send({
            code: 1,
            message: "日历消费总览 请求失败！",
            result: null,
        });
    }
});

export default calendarShowData;
